<template>
  <div class="payment-manage">
    <el-card class="box-card">
      <!-- 搜索工具栏 -->
      <div class="toolbar">
        <div class="search-box">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="订单号"
            clearable
            style="width: 200px"
          />
          <el-select v-model="queryParams.status" placeholder="支付状态" clearable>
            <el-option label="待支付" value="PENDING" />
            <el-option label="支付成功" value="SUCCESS" />
            <el-option label="已退款" value="REFUNDED" />
          </el-select>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </div>

      <!-- 支付记录表格 -->
      <el-table v-loading="loading" :data="paymentList">
        <el-table-column prop="orderNo" label="订单号" width="180">
          <template #default="{ row }">
            <el-link type="primary" @click="handleDetail(row)">{{ row.orderNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="appointmentTime" label="预约时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.appointmentTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="studentName" label="学生" />
        <el-table-column prop="counselorName" label="咨询师" />
        <el-table-column prop="totalAmount" label="总金额">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="platformFee" label="平台费用">
          <template #default="{ row }">
            ¥{{ row.platformFee }}
          </template>
        </el-table-column>
        <el-table-column prop="counselorAmount" label="咨询师收入">
          <template #default="{ row }">
            ¥{{ row.counselorAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.paymentStatus)">
              {{ getStatusLabel(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button 
              v-if="row.paymentStatus === 'SUCCESS'"
              link 
              type="warning" 
              @click="handleRefund(row)"
            >退款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 退款对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="退款"
      width="500px"
    >
      <el-form ref="refundFormRef" :model="refundForm" :rules="refundRules" label-width="100px">
        <el-form-item label="退款金额">
          <el-input-number 
            v-model="refundForm.amount"
            :min="0"
            :max="currentMaxAmount"
            :precision="2"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input
            v-model="refundForm.reason"
            type="textarea"
            rows="3"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRefund" :loading="refundLoading">
          确认退款
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailVisible"
      width="600px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder?.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ currentOrder?.appointmentTime }}</el-descriptions-item>
        <el-descriptions-item label="咨询师">{{ currentOrder?.counselorName }}</el-descriptions-item>
        <el-descriptions-item label="学生">{{ currentOrder?.studentName }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder?.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="平台费用">¥{{ currentOrder?.platformFee }}</el-descriptions-item>
        <el-descriptions-item label="咨询师收入">¥{{ currentOrder?.counselorAmount }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">{{ currentOrder?.paymentStatus }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ currentOrder?.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ currentOrder?.paymentTime }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentOrder?.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentOrder?.updateTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { PaymentStatus, PaymentQuery, PaymentRecord, RefundForm } from '@/types/payment'
import { getPaymentList, applyRefund } from '@/api/payment'
import dayjs from 'dayjs' // 确保已经安装并导入 dayjs

// 查询参数
const queryParams = ref<PaymentQuery>({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  status: undefined
})

// 支付列表
const paymentList = ref<PaymentRecord[]>([])
const total = ref(0)
const loading = ref(false)

// 日期范围
const dateRange = ref<[Date, Date] | null>(null)

// 退款表单
const refundForm = ref<RefundForm>({
  orderId: 0,
  amount: 0,
  reason: ''
})

// 退款对话框可见性
const refundDialogVisible = ref(false)

// 退款表单验证规则
const refundRules = {
  reason: [
    { required: true, message: '请输入退款原因', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 退款加载状态
const refundLoading = ref(false)

// 当前最大退款金额
const currentMaxAmount = ref(0)

// 添加详情对话框相关变量
const detailVisible = ref(false)
const currentOrder = ref<any>(null)

// 获取状态标签类型
const getStatusType = (status: PaymentStatus) => {
  const map: Record<PaymentStatus, string> = {
    PENDING: 'warning',
    SUCCESS: 'success',
    REFUNDED: 'info'
  }
  return map[status] || 'info'
}

// 获取状态显示文本
const getStatusLabel = (status: PaymentStatus) => {
  const map: Record<PaymentStatus, string> = {
    PENDING: '待支付',
    SUCCESS: '已支付',
    REFUNDED: '已退款'
  }
  return map[status] || status
}

// 日期格式化函数
const formatDateTime = (time: string) => {
  if (!time) return '-'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 获取列表数据
const handleQuery = async () => {
  console.log('=== 开始查询支付列表 ===')
  console.log('查询参数:', JSON.stringify(queryParams.value, null, 2))
  
  loading.value = true
  try {
    const { data } = await getPaymentList(queryParams.value)
    console.log('=== API 响应数据 ===')
    console.log('完整响应:', data)
    
    // 直接使用返回的分页数据
    paymentList.value = data.records || []
    total.value = data.records?.length || 0
    
    console.log('=== 更新后的数据 ===')
    console.log('列表数据:', paymentList.value)
    console.log('总数:', total.value)
    
  } catch (error) {
    console.error('=== 查询异常 ===')
    console.error('错误详情:', error)
    ElMessage.error('获取支付列表失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderNo: '',
    status: undefined,
    startDate: undefined,
    endDate: undefined
  }
  dateRange.value = null
  handleQuery()
}

// 监听日期范围变化
watch(dateRange, (newVal) => {
  console.log('=== 日期范围变化 ===')
  console.log('新的日期范围:', newVal)
  
  if (newVal) {
    const startDate = newVal[0]?.toISOString().split('T')[0]
    const endDate = newVal[1]?.toISOString().split('T')[0]
    console.log('处理后的开始日期:', startDate)
    console.log('处理后的结束日期:', endDate)
    
    queryParams.value.startDate = startDate
    queryParams.value.endDate = endDate
  } else {
    console.log('清空日期范围')
    queryParams.value.startDate = undefined
    queryParams.value.endDate = undefined
  }
  
  console.log('更新后的查询参数:', JSON.stringify(queryParams.value, null, 2))
  handleQuery()
})

// 查看详情
const handleDetail = (row: PaymentRecord) => {
  currentOrder.value = row
  detailVisible.value = true
}

// 处理退款
const handleRefund = (row: PaymentRecord) => {
  console.log('处理退款，订单:', row)
  if (row.id && row.totalAmount) {
    currentMaxAmount.value = row.totalAmount
    refundForm.value = {
      orderId: row.id,
      amount: row.totalAmount,
      reason: ''
    }
    console.log('退款表单初始化:', refundForm.value)
    refundDialogVisible.value = true
  }
}

// 提交退款
const submitRefund = async () => {
  console.log('提交退款，表单数据:', refundForm.value)
  refundLoading.value = true
  try {
    const res = await applyRefund(refundForm.value)
    console.log('退款响应:', res)
    refundDialogVisible.value = false
    ElMessage.success('退款成功')
    handleQuery()
  } catch (error) {
    console.error('退款失败，错误:', error)
    ElMessage.error('退款失败')
  } finally {
    refundLoading.value = false
  }
}

// 分页方法
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val
  handleQuery()
}

// 初始化加载
handleQuery()
</script>

<style lang="scss" scoped>
.payment-manage {
  padding: 20px;

  .toolbar {
    margin-bottom: 20px;

    .search-box {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;

      .el-select {
        width: 120px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
